// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.model.dao.impl;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.CarDAO;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Car DAO implementation
 * @author Andrei Senchuk
 */
public class CarDAOImpl extends HibernateDaoSupport implements CarDAO {
    private static final Log logger = LogFactory.getLog(CarDAOImpl.class);
    
    public Car findById(Long id) {
        return getHibernateTemplate().load(Car.class, id);
    }

    @SuppressWarnings("unchecked")
    public List<Car> findByOwnerId(Long id) {
        List<Car> cars = (List<Car>)getHibernateTemplate().find("from Car car where user = ? order by car.brand, car.model", String.valueOf(id));
        return cars;
    }

    public void save(Car car) {
        getHibernateTemplate().saveOrUpdate(car);
    }

    public Car findByOwnerAndId(User owner, Long id) {
        try {
            List list = getHibernateTemplate().find("from Car where owner = ? and id = ?", owner, id);
            return (Car)list.get(0);
        } catch(IndexOutOfBoundsException e) {
            return null;
        }
    }

    public void remove(Car obj) {
        getHibernateTemplate().delete(obj);
    }
}
